#encoding=utf-8
'''
Created on 2012-12-28

@author: Administrator
'''
from config.settings import DATABASES
from django.forms.models import model_to_dict
from django.shortcuts import render_to_response
from django.template.context import Context
from django.template.loader import get_template
from tool import temp_map as map
import MySQLdb
import os
from MySQLdb.cursors import DictCursor

path=os.path.abspath(os.curdir)+'/yqy/html/templates'
defVersion='1.0'
myCfg={
   'root':'yqy',
   'pageTitle':'首页',
   'my_config':{
            'debug':True
        }
   }
def createHtml(cfg,isResponse=False):
    retBean=[]
    itemPath=None
    for item in cfg:
        if item.get("version"):
            version=item.get("version")
        else:
            version=defVersion
        itemPath="common/"+item.get("key")+version+".html"
        if item.has_key('noescape') and item['noescape']:
            retBean.append(renderNoescape(itemPath,item))
        else:
            retBean.append(renderField(itemPath,item))
        
    if isResponse:
        return "".join(retBean)
    else:
        return {'result':'200',"content":"<div class='formItem'>"+"".join(retBean)+"</div>"}
    
def createBaseHtml(cfg):
    retBean=[]
    itemPath=None
    for item in cfg:
        if item.get("version"):
            version=item.get("version")
        else:
            version=defVersion
        itemPath="common/"+item.get("key")+version+".html"
        t = get_template(itemPath)
        retBean.append(t.render(Context({'item':item})))
   
    extend="<div class='formItem fullScreen'>"+"".join(retBean)+"</div>"
    
    base =get_template('base/head.html').render(Context(myCfg))
    
    return base+extend

def getQueryHtml(bean):
    
    return get_template('base/edit.html').render(Context({'item':bean}))

def toDict(obj):
    return model_to_dict(obj)

def render(filePath,param):
    temp = get_template(filePath) 
    return temp.render(Context(param))
        
def renderField(filePath,param):
    temp = get_template(filePath) 
    return temp.render(Context({'item':param}))

def renderNoescape(filePath,param):
    temp = get_template(filePath) 
    context=Context({'item':param})
    #取消自动编码 html内容
    context.autoescape=False
    return temp.render(context)

def retHtml(name,param):
    
    return render_to_response(map[name], myCfg)  
    
def retError(mes):
    return {'result':800,"message":mes}

def retSuccess(mes):
    return {'result':200,"message":mes}
 
def getFilePrefix(name):
    index=name.rfind(".")
    if(index!=-1):
        return name[index:]

def getDictDb():
    cfg=DATABASES['default']
    db = MySQLdb.connect(user=cfg['USER'], db=cfg['NAME'], passwd=cfg['PASSWORD'], host=cfg['HOST'],charset='utf8')
    return db
def execPage(sql,page={'page':0,'pageSize':15}):
    aSql=sql+" limit "+str(int(page.get("page"))-1)+","+page.get("pageSize")
    db=getDictDb()
    cursor = db.cursor(DictCursor)
    cursor.execute(aSql)
    res =[]
    temp={}
    for row in cursor.fetchallDict():
        res.append(row)
    
    t_num=0
    sql="select count(*) total from ("+sql+") a";
    cursor.execute(sql)
    for row in cursor.fetchallDict():
        t_num=row['total']
    temp['rows']=res
    temp['total']=t_num
    db.close()
    return temp
    
def execMysql(sql):
    db=getDictDb()
    cursor = db.cursor(DictCursor)
    cursor.execute(sql)
    res =[]
    for row in cursor.fetchallDict():
        res.append(row)
    db.close()
    return res

def getSelectText(subs,val):
    for item in subs:
        if item['id']==val:
            return item['text']
    return val    
    